package com.jxdinfo.hussar.example.mes.pro.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jxdinfo.hussar.example.common.config.PropertyConfig;
import com.jxdinfo.hussar.example.mes.pro.dao.ProFeedbackMapper;
import com.jxdinfo.hussar.example.mes.pro.domain.Erp.CompRptDatas;
import com.jxdinfo.hussar.example.mes.pro.domain.Erp.ErpRse;
import com.jxdinfo.hussar.example.mes.pro.service.IErpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 生产报工记录Service业务层处理
 *
 * @author yinjinlu
 * @date 2022-07-10
 */
@Service
public class ErpServiceImpl implements IErpService
{
    private static final Logger logger = LoggerFactory.getLogger(ErpServiceImpl.class);

    @Resource
    private PropertyConfig propertyConfig1;

    private  static PropertyConfig propertyConfig;

    @PostConstruct
    public void init() {
        propertyConfig = propertyConfig1;
    }

    @Override
    public JSONObject proFeedbackToErp(CompRptDatas compRptDatas)
    {
        //1、调用erp接口获取到token
        RestTemplate tokenRestTemplate = new RestTemplate();
        String url = "http://" + propertyConfig.getIp() + "/U9C/webapi/OAuth2/AuthLogin?clientid=123456&clientsecret=f01ae41aca594ac785bedeae241641ae&entCode=01&userCode=demo1&orgCode=001&api_key=Login";
        JSONObject json = tokenRestTemplate.getForEntity(url, JSONObject.class).getBody();
        ErpRse tokenErpRse = JSONObject.parseObject(JSONObject.toJSONString(json), ErpRse.class);
        String token = tokenErpRse.getData();
        //2、新增完工报告
        // 请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Token", token);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        List<CompRptDatas> compRptDatasList = new ArrayList<>();
        compRptDatasList.add(compRptDatas);

//        logger.info(JSON.toJSONString(compRptDatasList));

        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(compRptDatasList), httpHeaders);
        String createUrl = "http://" + propertyConfig.getIp() + "/U9C/webapi/CompleteDoc/Create";
        // 发送请求
        ResponseEntity<String> entity = tokenRestTemplate.postForEntity(createUrl, httpEntity, String.class);
        // 获取请求回调
        // 打印请求返回信息
//        System.out.println(jsonObject.toJSONString());
        return JSONObject.parseObject(JSON.toJSON(entity.getBody()).toString());
    }
}
